import ConnMySql
import ConnMongo
import yaml
from JKlog import *
import datetime
import json


class MemberData:
    def __init__(self, Code, Name, Phone, Id):
        self.Code = Code
        self.Name = Name
        self.PHONE = Phone
        self.ID = Id


class AccountData:
    def __init__(self, Code, Id):
        self.Code = Code
        self.ID = Id


class MonogoData:
    def __init__(self, Id, Phone):
        self.PHONE = Phone
        self.ID = Id


class ConsistentData:
    def __init__(self, strConfig):
        fr = open('Config.yml', 'r')
        fconfig = yaml.load(fr)
        self.realConfig = fconfig[strConfig]
        self.account = []
        self.member = []
        self.monogo = []
        self.result = {}

    def connectDB(self, dbName):
        memsum = self.realConfig[dbName]
        host = memsum["host"]
        user = memsum["user"]
        pwd = memsum["password"]
        name = memsum["name"]
        port = memsum["port"]
        charset = memsum["charset"]
        mysqlDb = ConnMySql.ConnMySql(host, port, name, user, pwd, charset)
        return mysqlDb

    def connectMonogo(self):
        monogo = self.realConfig["monogo"]
        host = monogo["host"]
        port = monogo["port"]
        name = monogo["name"]
        colname = monogo["colname"]
        monUser = monogo["user"]
        monPwd = monogo["pwd"]
        mongodb = ConnMongo.ConnMongo(host, port, name, colname, monUser, monPwd)
        return mongodb

    def queryAllAccount(self):
        dbQueryAccount = 'SELECT * FROM tbl_account'
        dbAccountConnect = self.connectDB("account")
        AllAccount = dbAccountConnect.fetch_all(dbQueryAccount)
        for eachAccount in AllAccount:
            accountCode = eachAccount["CODE"]
            accountID = eachAccount["ID"]
            newAccount = AccountData(accountCode, accountID)
            self.account.append(newAccount)

    def queryAllMember(self):
        dbQueryMember = 'SELECT * FROM tbl_member'
        dbMemberConnect = self.connectDB("mem")
        AllMember = dbMemberConnect.fetch_all(dbQueryMember)
        for eachMember in AllMember:
            memCode = eachMember["CODE"]
            memID = eachMember["ID"]
            memName = eachMember["NICK_NAME"]
            memPhone = eachMember["PHONE"]
            newMemberData = MemberData(memCode, memName, memPhone, memID)
            self.member.append(newMemberData)

    def queryMonogoDB(self):
        monogoDB = self.connectMonogo()
        allMonogo = monogoDB.find_table_all()
        for eachMonogo in allMonogo:
            monogoID = eachMonogo["_id"]
            monogoPhone = eachMonogo["mobile"]
            newMonogo = MonogoData(monogoID, monogoPhone)
            self.monogo.append(newMonogo)

    # def CheckData(self,):


    def ConsistencyTask(self):
        nowDateString = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
        logger = JKLogger('Consistency' + "_" + nowDateString)
        try:
            self.queryMonogoDB()
            self.queryAllAccount()
            self.queryAllMember()
            for i in range(len(self.member) - 1, -1, -1):
                memberData = self.member[i]
                code = memberData.Code
                phone = memberData.PHONE

                accountResult = filter(lambda x: x.Code == code, self.account)
                monogoResult = filter(lambda x: x.ID == code and x.PHONE == phone, self.monogo)
                if accountResult and monogoResult:
                    self.account.remove(accountResult[0])
                    self.monogo.remove(monogoResult[0])
                    self.member.remove(memberData)
        except Exception as ex:
            logger.log("Exception:" + str(ex))
            self.result["Exception"] = ex.message
        logger.log("---------Member except----------")
        if self.member:
            self.result["member"] = self.member
            memLeft = json.dumps(self.member, default=lambda o: o.__dict__, sort_keys=False, indent=4)
            logger.log(memLeft)
        logger.log("---------Account except----------")
        if self.account:
            self.result["account"] = self.account
            accLeft = json.dumps(self.account, default=lambda o: o.__dict__, sort_keys=False, indent=4)
            logger.log(accLeft)
        logger.log("----------Monogo except----------")
        if self.monogo:
            self.result["monogo"] = self.monogo
            monogoLeft = json.dumps(self.monogo, default=lambda o: o.__dict__, sort_keys=False, indent=4)
            logger.log(monogoLeft)
        return self.result
